package com.itheima.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.pojo.User;
import com.itheima.service.IUservice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/users")
public class UserController {

    @Autowired
    IUservice iUservice;
    Result result =new Result();
    Result2 result2 =new Result2();

	//分页查询用户
    @GetMapping("/{currentPage}/{pageSize}")
    public Result selectByPage(@PathVariable  int currentPage,@PathVariable int pageSize) throws IOException {
        Page<User> userPage = new Page<>(currentPage, pageSize);
        Page<User> page = iUservice.page(userPage);
        List<User> records = page.getRecords();
        long total = page.getTotal();
        result2.setRows(records);
        result2.setTotalCount(total);
        System.out.println("1111111");
        result.setData(result2);
        result.setCode(Code.GET_OK);
        return result;
    }
    /**
     * 保存用户
     * @param user 用户数据
     */
    @PostMapping
    public Result add(@RequestBody  User user) {

        Result result = new Result();

        boolean save = iUservice.save(user);
        if (save)
        result.setCode(Code.SAVE_OK);
        return result;
    }

    /**
     * 根据用户id查询用户
     * @param id 用户id
     */
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable Integer id) {
        boolean b = iUservice.removeById(id);
        if (b)
            result.setCode(Code.DELETE_OK);
        return result;
    }

    /**
     * 更新用户
     * @param user 用户数据
     */
    @PutMapping
    public Result update(@RequestBody User user) {
        boolean b = iUservice.updateById(user);
        if (b)
            result.setCode(Code.UPDATE_OK);
        return result;
    }

}
